import numpy as np

from dynamic import track_show
from dynamic import get_hsv_from_file
import cv2
colors = ['red', 'green', 'blue', 'yellow']
selected_colors = 3


def calculate_roi_color_average(img, x, y, w, h):
    # 提取ROI
    roi = img[y:y + h, x:x + w]

    # 确保ROI不是空的
    if roi.size == 0:
        return None  # 或者你可以返回一个默认值，如(0, 0, 0)

    # 计算每个颜色通道的平均值
    b, g, r = cv2.split(roi)
    avg_b = int(np.mean(b))
    avg_g = int(np.mean(g))
    avg_r = int(np.mean(r))

    # 返回颜色平均值
    return (avg_b, avg_g, avg_r)


def calculate_average_color(contour, color_image):
    # 创建一个与原始图像大小相同的全零矩阵（掩码），但数据类型为uint8
    mask = np.zeros(color_image.shape[:2], dtype=np.uint8)

    # 使用fillPoly填充轮廓内部，这里使用白色（255）填充
    cv2.fillPoly(mask, [contour], (255))

    # 使用掩码来获取轮廓内部的像素
    roi_pixels = color_image[mask == 255]

    # 如果roi_pixels非空，计算（b，g，r）的平均值
    if roi_pixels.size > 0:
        avg_color = np.mean(roi_pixels, axis=0)
        # 返回一个包含B、G、R三种颜色平均值的元组
        return tuple(avg_color)
    else:
        print("No pixels found inside the contour.")
        return None


path = r'images/questions\1.jpg'
hsv_list = get_hsv_from_file()
if hsv_list:
    lower, upper = hsv_list[0]
    img = cv2.imread(path)
    if img is not None:
        mask = cv2.inRange(img, lower, upper)
        cv2.imshow('mask', mask)
        cv2.waitKey(0)
        contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        for c in contours:
            # 矩形逼近
            x, y, w, h = cv2.boundingRect(c)
            # roi = img[y:y+h, x:x+h]
            # val = calculate_roi_color_average(img, x, y, w, h)
            val = calculate_average_color(c, img)
            print(f"average:{val}")
            # cv2.imshow("test", roi)
            cv2.waitKey(0)
            cv2.putText(img,"color", (x-5, y-5), cv2.FONT_HERSHEY_SCRIPT_SIMPLEX, 3, val, 3)
            # 画出矩形
            cv2.rectangle(img, (x-5, y-5), (x + w + 5, y + h + 5), (0, 0, 0), 3)
        cv2.imshow('color', img)
        cv2.waitKey(0)